package com.usian.admin.service.impl

import com.alibaba.fastjson.JSON
import com.hankcs.hanlp.utility.SentencesUtil
import com.usian.admin.feign.ArticleFeign
import com.usian.admin.feign.WemediaFeign
import com.usian.admin.mapper.AdChannelMapper
import com.usian.admin.mapper.AdSensitiveMapper
import com.usian.admin.service.WemediaNewsAutoScanService
import com.usian.common.aliyun.util.GreeTextScan
import com.usian.common.aliyun.util.GreenImageScan
import com.usian.common.fastdfs.FastDFSClient
import com.usian.model.admin.dtos.NewsAuthDto
import com.usian.model.article.pojos.ApArticle
import com.usian.model.article.pojos.ApArticleConfig
import com.usian.model.article.pojos.ApArticleContent
import com.usian.model.common.dtos.PageResponseResult
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.model.wemedia.pojos.WmNews
import com.usian.utils.common.SensitiveWordUtil
import io.seata.spring.annotation.GlobalTransactional
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.lang.StringBuilder
import java.util.*

@Service
open class WemediaNewsAutoScanServiceImpl : WemediaNewsAutoScanService {



    @Autowired
    private lateinit var wemediaFeign: WemediaFeign

    @Autowired
    private lateinit var articleFeign: ArticleFeign

    @Autowired
    private lateinit var adChannelMapper: AdChannelMapper

    @Autowired
    private lateinit var greenImageScan: GreenImageScan

    @Autowired
    private lateinit var greenTextScan: GreeTextScan

    @Autowired
    private lateinit var fastDFSClient: FastDFSClient

    @Value("\${fdfs.url}")
    private lateinit var baseUrl: String

    @Autowired
    private lateinit var sensitiveMapper: AdSensitiveMapper
@GlobalTransactional
    override fun autoScanByMediaNewsId(id: Long): ResponseResult<*>? {
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        val wmNews = wemediaFeign.findById(id.toInt())
                ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)
        wmNews.run {
            if (status == 4.toShort() || (status == 8.toShort() && publishTime.time <= System.currentTimeMillis())) saveAppArticle(this)
            if (status == 1.toShort()) {
                var text = StringBuilder() //即将拼接的所有文本内容
                val imageList: MutableList<String> = mutableListOf() //即将组合的所有图片
                JSON.parseArray(content).forEach {
                    val parseObject = JSON.parseObject(it.toString())
                    if (parseObject["type"] == "text") text.append(parseObject["value"])
                    else imageList.add(parseObject["value"].toString())
                }
                if (images.isNotBlank()) {//新闻对象中的封面图
                    imageList.addAll(images.split(","))
                }
                //文本审核
                greenTextScan.greeTextScan(text.toString())["suggestion"].let {
                    if (it != "pass"){
                        if (it == "block"){
                            reason="文章内容中有敏感词汇"
                            status=2
                        }
                        if (it == "revice"){
                            reason="文章内容中有不确定词汇"
                            status = 3
                        }
                        wemediaFeign.updateWmNews(this)
                        return ResponseResult.okResult(0,"审核未通过")
                    }
                }
                var byteList : MutableList<ByteArray> = mutableListOf()
                imageList.forEach {
                    val ti =it.replace(baseUrl,"")
                    val i = ti.indexOf("/")
                    byteList.add(fastDFSClient.download(ti.substring(0,i),ti.substring(i+1)))
                }
                //图片审核
                greenImageScan.imageScan(byteList)["suggestion"].let {
                    if (it != "pass"){
                        if (it == "block"){
                            reason="文章中图片有违规"
                            status=2
                        }
                        if (it == "revice"){
                            reason="文章图片有不确定元素"
                            status = 3
                        }
                        wemediaFeign.updateWmNews(this)
                        return ResponseResult.okResult(0,"审核未通过")
                    }
                }
                //敏感词过滤
                sensitiveMapper.findAllSensitive().let {
                    SensitiveWordUtil.initMap(it)
                    val matchWords = SensitiveWordUtil.matchWords(text.toString())
                    if (matchWords.isNotEmpty()){
                        status = 2
                        reason="内容中包含敏感词"
                        wemediaFeign.updateWmNews(this)
                        return ResponseResult.okResult(0,"审核失败")
                    }
                }
                if (publishTime.time > System.currentTimeMillis()){//审核通过，但是发布时间未到
                    status=8
                    wemediaFeign.updateWmNews(this)
                    return ResponseResult.okResult(0,"审核通过待发布")
                }
                saveAppArticle(this)

                return ResponseResult.okResult(0,"已发布")
            }
        }

        return null
    }

    open fun saveAppArticle(wmNews: WmNews) {
        val apArticle = ApArticle().run {
            title=wmNews.title
            layout=wmNews.type
            images=wmNews.images
            createdTime= Date()
            val wmUser = wemediaFeign.findWmUserById(wmNews.userId)
            if (wmUser != null){
                val author = articleFeign.findByName(wmUser.name)
                authorId=author.id.toLong()
                authorName=author.name
                adChannelMapper.selectById(wmNews.channelId).let {
                    channelId=it.id
                    channelName=it.name
                }
            }
            articleFeign.saveArticle(this)
        }
        articleFeign.saveArticleConfig(ApArticleConfig().apply {
            articleId=apArticle.id
            isForward=true
            isDelete=false
            isDown=true
            isComment=true
        })
        articleFeign.saveArticleContent(ApArticleContent().apply {
            articleId=apArticle.id
            content=wmNews.content
        })
        wmNews.status=9
        wmNews.reason="审核通过"
        wemediaFeign.updateWmNews(wmNews)
       /* //自治异常********除0异常
        var a=10/0*/
    }
    override fun findNews(dto: NewsAuthDto): PageResponseResult {
//分页查询
        val pageResponseResult= wemediaFeign.findList(dto).apply {
            //有图片需要显示，需要fasfdfs服务器地址
            host=baseUrl
            return this
        }
    }

    override fun findOne(id: Int?): ResponseResult<*> {
//检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID)
        }
        //查询数据
        val findWmNewsVo = wemediaFeign.findWmNewsVo(id)
        //结构封装
        val responseResult = ResponseResult.okResult(findWmNewsVo)
        responseResult.host = baseUrl
        return responseResult
    }

    override fun updateStatus(type: Int?, dto: NewsAuthDto): ResponseResult<*> {
//1.参数检查
        if (dto == null || dto.id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID)
        }
        //2.查询文章
        val wmNews = wemediaFeign.findById(dto.id) ?: return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST)
//3.审核没有通过
        if (type == 0) {
            val wmNews=wmNews.run {
                status=2
                reason=dto.msg
                wemediaFeign.updateWmNews(this)
            }

        } else if (type == 1) {
            //4.人工审核通过
            val wmNews=wmNews.run {
                status=4
                reason="人工审核通过"
                wemediaFeign.updateWmNews(this)
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)
    }
}